<template>
  <div class="book-detail">
    <NavBar />
    <LoadingSpinner v-if="isLoading || isCoverLoading" message="加载图书详情..." />
    <main class="container" v-else-if="book">
      <div class="back-link">
        <router-link to="/">
          &lt; 返回首页
        </router-link>
      </div>
      
      <div class="book-content">
        <div class="book-image">
          <img :src="coverUrl" :alt="book.title">
          <button @click="debugCoverInfo" class="debug-btn">调试封面信息</button>
        </div>
        
        <div class="book-details">
          <div class="book-header">
          <h1>{{ book.title }}</h1>
            <div class="view-count">
              <el-icon><View /></el-icon>
              <span>{{ book.views || 0 }}</span>
            </div>
          </div>
          <p class="book-author">作者: {{ book.author }}</p>
          <div class="book-price">¥{{ book.price }}</div>
          
          <div class="book-condition">
            <h3>书籍状态</h3>
            <div class="condition-meter">
              <div class="meter-fill" :style="{ width: `${book.new_degree}%` }"></div>
            </div>
            <p>{{ getConditionText(book.book_condition, book.new_degree) }}</p>
          </div>
          
          <div class="seller-info">
            <h3>卖家信息</h3>
            <p>卖家: {{ book.seller_name }}</p>
            <p>学院: {{ book.department || '未知' }}</p>
          </div>
          
          <div class="book-info">
            <h3>书籍信息</h3>
            <p>分类: {{ book.category || '未分类' }}</p>
            <p>上架时间: {{ formatDate(book.created_at) }}</p>
          </div>
          
          <div class="book-description">
            <h3>书籍描述</h3>
            <p>{{ book.description || '暂无描述' }}</p>
          </div>
          
          <div class="action-buttons">
            <button class="btn-buy" @click="buyBook">立即购买</button>
            <button class="btn-contact" @click="contactSeller">联系卖家</button>
            <button class="btn-favorite" @click="toggleFavorite" :disabled="isCheckingFavorite">
              <el-icon v-if="!isCheckingFavorite" :color="isFavorite ? '#F7BA2A' : '#909399'" class="favorite-icon">
                <star-filled v-if="isFavorite" />
                <star v-else />
              </el-icon>
              <span v-else class="loading-icon"></span>
              {{ isCheckingFavorite ? '加载中...' : (isFavorite ? '取消收藏' : '加入收藏') }}
            </button>
            <button class="btn-report" @click="openReportModal">举报</button>
          </div>
        </div>
      </div>
      
      <div class="recommended-books">
        <h2>推荐书籍</h2>
        <div class="related-grid" v-if="recommendedBooks.length > 0">
          <div class="related-book" v-for="recBook in recommendedBooks" :key="recBook.id" @click="viewBookDetails(recBook.id)">
            <img :src="getRecommendedCoverUrl(recBook)" :alt="recBook.title">
            <div class="related-info">
              <h4>{{ recBook.title }}</h4>
              <p>¥{{ recBook.price }}</p>
            </div>
          </div>
        </div>
        <div class="no-recommendations" v-else>
          <p>没有相似的书籍</p>
        </div>
      </div>
    </main>
    
    <div class="contact-modal" v-if="showContactModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>联系卖家</h3>
          <button class="close-btn" @click="showContactModal = false">×</button>
        </div>
        <div class="modal-body">
          <p>卖家: {{ book.seller_name }}</p>
          <p>微信: {{ seller.wechat || '暂未提供' }}</p>
          <p>电话: {{ seller.phone || '暂未提供' }}</p>
          <textarea v-model="contactMessage" placeholder="输入你想对卖家说的话..."></textarea>
          <button class="send-btn" @click="sendMessage">发送消息</button>
        </div>
      </div>
    </div>

    <!-- 举报模态框 -->
    <div class="report-modal" v-if="showReportModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>举报</h3>
          <button class="close-btn" @click="showReportModal = false">×</button>
        </div>
        <div class="modal-body">
          <div class="report-form">
            <div class="form-group">
              <label for="report-reason">举报原因</label>
              <select id="report-reason" v-model="reportData.reason">
                <option value="">请选择举报原因</option>
                <option value="fake">虚假信息</option>
                <option value="inappropriate">不适内容</option>
                <option value="scam">欺诈行为</option>
                <option value="other">其它原因</option>
              </select>
            </div>
            
            <div class="form-group">
              <label for="report-description">详细描述</label>
              <textarea 
                id="report-description" 
                v-model="reportData.details"
                placeholder="请详细描述举报原因和相关证据..."
                rows="5"
              ></textarea>
            </div>
            
            <div class="report-info">
              <p><strong>被举报卖家ID:</strong> {{ book.seller_id }}</p>
              <p><strong>书籍ID:</strong> {{ book.id }}</p>
              <p><strong>卖家名称:</strong> {{ book.seller_name }}</p>
              <p><strong>书籍名称:</strong> {{ book.title }}</p>
            </div>
            
            <div class="form-actions">
              <button 
                class="btn-submit" 
                @click="submitReport"
                :disabled="isSubmitting"
              >
                {{ isSubmitting ? '提交中...' : '提交举报' }}
              </button>
              <button class="btn-cancel" @click="showReportModal = false">取消</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import { View, Star, StarFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import defaultCover from '@/assets/OIP.jpg'

const route = useRoute()
const router = useRouter()
const bookId = computed(() => route.params.id)
const book = ref(null)
const recommendedBooks = ref([])
const isFavorite = ref(false)
const isCheckingFavorite = ref(true)
const showContactModal = ref(false)
const contactMessage = ref('')
const seller = ref({})
const isLoading = ref(true)
const coverUrl = ref(defaultCover)
const isCoverLoading = ref(true)
const showReportModal = ref(false)
const reportData = ref({})
const isSubmitting = ref(false)

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchBookDetails(newId)
  }
})

onMounted(() => {
  fetchBookDetails(bookId.value)
})

// 获取书籍详情
const fetchBookDetails = async (id) => {
  try {
    isLoading.value = true
    isCoverLoading.value = true
    isCheckingFavorite.value = true
    console.log('获取书籍详情，ID:', id)
    
    // 同时发起多个请求，提高页面加载效率
    const [bookResponse, favoritesResponse] = await Promise.all([
      api.book.getDetail(id),
      api.favorite.getFavoriteBooks()
    ])
    
    console.log("原始响应:", bookResponse)
    
    // 处理书籍详情响应数据
    if (bookResponse) {
      // 根据响应的结构判断
      if (bookResponse.code === 200 && bookResponse.data) {
        // 标准格式: {code, message, data}
        book.value = bookResponse.data
      } else if (bookResponse.id) {
        // API可能直接返回了数据对象
        book.value = bookResponse
      } else {
        console.error('获取书籍详情失败: 无法识别的响应格式', bookResponse)
        book.value = null
        isLoading.value = false
        isCoverLoading.value = false
        return
      }
      
      console.log('获取书籍详情成功:', book.value)
      
      // 预先增加本地浏览次数，避免闪烁
      if (book.value && typeof book.value.views === 'number') {
        // 先在本地增加浏览次数，然后异步调用API
        book.value.views += 1
      }
      
      // 处理收藏状态响应
      processCheckFavorite(favoritesResponse, id)
      
      // 异步增加浏览次数
      incrementViewCount(id)
      
      // 获取推荐书籍
      fetchRecommendedBooks(id)
      
      // 获取书籍封面并等待完成
      try {
        await loadBookCover()
        console.log('封面加载完成')
      } catch (error) {
        console.error('封面加载失败，使用默认封面:', error)
        coverUrl.value = defaultCover
      } finally {
        isCoverLoading.value = false
      }
      
      // 在封面加载完成后结束页面的加载状态
      isLoading.value = false
    } else {
      console.error('获取书籍详情失败: 响应为空')
      book.value = null
      isLoading.value = false
      isCoverLoading.value = false
    }
  } catch (error) {
    console.error('获取书籍详情失败:', error)
    book.value = null
    isLoading.value = false
    isCoverLoading.value = false
  } finally {
    isCheckingFavorite.value = false
  }
}

// 处理收藏状态检查的响应
const processCheckFavorite = (response, bookId) => {
  try {
    console.log('检查是否收藏，书籍ID:', bookId)
    console.log('获取收藏书籍列表成功:', response)
    
    let favoriteBooks = []
    
    // 根据响应格式处理数据
    if (Array.isArray(response)) {
      favoriteBooks = response
    } else if (response && response.code === 200 && Array.isArray(response.data)) {
      favoriteBooks = response.data
    }
    
    // 检查当前书籍是否在收藏列表中
    isFavorite.value = favoriteBooks.some(book => book.id === parseInt(bookId))
    
    console.log('当前书籍收藏状态:', isFavorite.value ? '已收藏' : '未收藏')
  } catch (error) {
    console.error('处理收藏状态失败:', error)
    isFavorite.value = false
  } finally {
    isCheckingFavorite.value = false
  }
}

// 根据书籍状态获取文字描述
const getConditionText = (condition, newDegree) => {
  if (!condition) return '未知'
  
  switch(condition) {
    case 'new': return `几乎全新 (${newDegree || 90}%新)`
    case 'good': return `品相良好 (${newDegree || 70}%新)`
    case 'used': return `有使用痕迹 (${newDegree || 50}%新)`
    default: return '未知状态'
  }
}

// 增加浏览次数
const incrementViewCount = async (bookId) => {
  try {
    await api.book.addViews(bookId)
    console.log('增加浏览次数成功')
    // 不再更新本地浏览次数，因为已经在获取详情后预先增加了
  } catch (error) {
    console.error('增加浏览次数失败:', error)
    // 即使API调用失败，也保持本地浏览次数的增加，避免闪烁
  }
}

// 创建预加载图片的函数
const preloadImage = (url) => {
  // 如果URL为空，则直接加载默认图片
  if (!url) {
    console.error('图片URL为空，使用默认图片');
    coverUrl.value = defaultCover;
    return Promise.resolve();
  }
  
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      console.log('图片加载成功:', url)
      coverUrl.value = url
      resolve(url)
    }
    img.onerror = () => {
      console.error('图片加载失败:', url)
      // 加载失败时设置默认封面而不是抛出错误
      coverUrl.value = defaultCover
      // 使用resolve而不是reject，避免中断流程
      resolve(defaultCover)
    }
    img.src = url
  })
}

// 修正URL构建逻辑
const buildCoverUrl = (path) => {
  // 如果path不存在，返回空字符串
  if (!path) return '';
  
  try {
    // 检查是否为相对路径，添加基础URL
    if (typeof path === 'string') {
      if (path === 'true' && book.value && book.value.id) {
        // 如果cover字段是'true'，使用API路径
        return `http://localhost:8080/api/user/book/cover/${book.value.id}`;
      } else if (!path.startsWith('http')) {
        // 对路径进行URL编码，确保特殊字符不会导致问题
        const encodedPath = path.split('/').map(segment => encodeURIComponent(segment)).join('/');
        console.log('编码后的封面路径:', encodedPath);
        return `http://localhost:8080/${encodedPath}`;
      }
      return path;
    }
    
    // 如果path是布尔值true，则通过书籍ID构建API路径
    if (path === true && book.value && book.value.id) {
      return `http://localhost:8080/api/user/book/cover/${book.value.id}`;
    }
    
    // 如果path不是字符串也不是布尔值，返回空字符串
    console.log('封面格式不正确');
    return '';
  } catch (error) {
    console.error('处理封面URL时出错:', error);
    return '';
  }
}

// 获取封面图片
const loadBookCover = async () => {
  try {
    console.log('开始加载封面，书籍数据:', book.value);
    
    // 设置默认封面
    coverUrl.value = defaultCover;
    
    if (book.value) {
      const coverData = book.value.cover;
      console.log('封面数据:', coverData);
      
      if (!coverData) {
        console.log('无封面数据，使用默认封面');
        coverUrl.value = defaultCover;
        return;
      }
      
      // 处理封面URL
      if (typeof coverData === 'string') {
        // 根据不同的封面数据格式处理
        if (coverData === 'true') {
          // 如果封面字段是'true'字符串，使用下载接口直接获取JSON数据
          console.log('检测到cover=true，使用接口获取封面信息...');
          
          try {
            // 获取封面信息（非blob格式），因为服务器返回JSON而不是图片数据
            const response = await api.book.getCover(book.value.id);
            console.log('获取封面信息成功:', response);
            
            // 解析响应中的cover字段（如果有的话）
            if (response && response.cover) {
              // 如果cover字段是相对路径，构建完整URL
              if (typeof response.cover === 'string' && !response.cover.startsWith('http')) {
                const encodedPath = response.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
                const fullUrl = `http://localhost:8080/${encodedPath}`;
                console.log('从API构建的封面完整URL:', fullUrl);
                
                // 使用Image对象加载图片
                const img = new Image();
                img.onload = () => {
                  coverUrl.value = fullUrl;
                  console.log('封面图片加载成功');
                  isCoverLoading.value = false;
                };
                img.onerror = () => {
                  console.error('封面图片加载失败:', fullUrl);
                  coverUrl.value = defaultCover;
                  isCoverLoading.value = false;
                };
                img.src = fullUrl;
                return;
              } else if (response.cover.startsWith('http')) {
                // 如果已经是完整URL
                coverUrl.value = response.cover;
                console.log('使用API返回的完整URL:', response.cover);
                isCoverLoading.value = false;
                return;
              }
            } else {
              console.error('API响应中没有有效的cover字段');
              coverUrl.value = defaultCover;
            }
          } catch (error) {
            console.error('获取封面信息失败:', error);
            coverUrl.value = defaultCover;
          }
        } else if (!coverData.startsWith('http')) {
          // 相对路径，添加基础URL
          const encodedPath = coverData.split('/').map(segment => encodeURIComponent(segment)).join('/');
          const fullUrl = `http://localhost:8080/${encodedPath}`;
          console.log('编码后的封面完整路径:', fullUrl);
          
          // 使用Image对象加载图片
          const img = new Image();
          img.onload = () => {
            coverUrl.value = fullUrl;
            console.log('图片加载成功');
          };
          img.onerror = () => {
            console.error('图片加载失败:', fullUrl);
            coverUrl.value = defaultCover;
          };
          img.src = fullUrl;
        } else {
          // 已经是完整URL
          coverUrl.value = coverData;
          console.log('使用完整URL:', coverData);
        }
      } else {
        console.log('封面格式不正确，使用默认封面');
        coverUrl.value = defaultCover;
      }
    }
  } catch (error) {
    console.error('加载封面出错:', error);
    coverUrl.value = defaultCover;
  } finally {
    // 确保加载状态被取消
    setTimeout(() => {
      isCoverLoading.value = false;
    }, 300);
  }
}

// 获取推荐书籍
const fetchRecommendedBooks = async (bookId) => {
  try {
    console.log('获取推荐书籍，书籍ID:', bookId)
    
    // 调用推荐API
    const response = await api.book.recommend(bookId)
    
    console.log('推荐书籍响应:', response)
    
    if (Array.isArray(response)) {
      recommendedBooks.value = response
    } else if (response && response.code === 200 && response.data) {
      recommendedBooks.value = response.data
    } else if (response && Array.isArray(response.data)) {
      recommendedBooks.value = response.data
    } else {
      recommendedBooks.value = []
    }
    
    console.log('获取推荐书籍成功:', recommendedBooks.value)
  } catch (error) {
    console.error('获取推荐书籍失败:', error)
    recommendedBooks.value = []
  }
}

// 获取推荐书籍的封面URL
const getRecommendedCoverUrl = (book) => {
  if (!book || !book.cover) {
    console.log('推荐书籍无封面数据，使用默认封面');
    return defaultCover;
  }
  
  try {
    // 检查是否为相对路径，添加基础URL
    if (typeof book.cover === 'string') {
      if (!book.cover.startsWith('http')) {
        // 对路径进行URL编码，确保特殊字符不会导致问题
        const encodedPath = book.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
        console.log('推荐书籍编码后的封面路径:', encodedPath);
        return `http://localhost:8080/${encodedPath}`;
      }
      return book.cover;
    }
    
    // 如果book.cover不是字符串，使用默认封面
    console.log('推荐书籍封面格式不正确，使用默认封面');
    return defaultCover;
  } catch (error) {
    console.error('获取推荐书籍封面URL时出错:', error);
    return defaultCover;
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
  } catch (e) {
    return dateString
  }
}

const contactSeller = () => {
  // 获取当前用户ID和卖家ID
  const currentUserId = localStorage.getItem('userId')
  const sellerId = book.value.seller_id
  
  if (!currentUserId) {
    ElMessage.error('请先登录后再联系卖家')
    router.push('/login')
    return
  }
  
  // 检查是否是自己的书籍
  if (parseInt(currentUserId) === parseInt(sellerId)) {
    ElMessage.warning('这是您自己发布的书籍，不能联系自己')
    return
  }
  
  // 跳转到消息页面，并传递必要参数
  router.push({
    path: '/messages',
    query: {
      bookId: book.value.id,
      sellerId: sellerId,
      bookTitle: book.value.title,
      sellerName: book.value.seller_name
    }
  })
}

const toggleFavorite = async () => {
  try {
    // 调用新的收藏/取消收藏双功能接口
    await api.book.toggleFavorite(bookId.value)
    
    // 切换收藏状态
  isFavorite.value = !isFavorite.value
    
    console.log(isFavorite.value ? '收藏成功' : '取消收藏成功')
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    // 操作失败时提醒用户
    alert(isFavorite.value ? '取消收藏失败' : '收藏失败')
  }
}

const sendMessage = () => {
  // 在真实项目中，这里会调用API发送消息
  alert('消息已发送给卖家！')
  showContactModal.value = false
  contactMessage.value = ''
}

// 点击立即购买按钮，生成订单
const buyBook = async () => {
  try {
    // 显示加载状态
    isLoading.value = true
    
    // 构建订单数据，包含书籍ID
    const orderData = {
      books: [{ book_id: bookId.value }],
      remark: '' // 可以添加备注字段，此处为空
    }
    
    console.log('提交订单数据:', orderData)
    
    // 调用生成订单API
    const response = await api.orders.generate(orderData)
    console.log('订单生成成功:', response)
    
    // 将订单数据传递给订单历史页面
    // 使用localStorage临时存储订单数据，避免刷新页面数据丢失
    localStorage.setItem('pendingOrderData', JSON.stringify(response))
    
    // 获取订单ID
    let orderId = null
    if (response && response.orderId) {
      orderId = response.orderId
    } else if (response && response.id) {
      orderId = response.id
    } else if (response && response.order_id) {
      orderId = response.order_id
    }
    
    // 存储当前需要支付的订单ID
    if (orderId) {
      localStorage.setItem('currentPayOrderId', orderId)
    }
    
    // 显示成功消息
    ElMessage.success('订单生成成功，即将跳转到订单历史页面')
    
    // 直接跳转到订单历史页面
    router.push('/transactions')
  } catch (error) {
    console.error('生成订单失败:', error)
    
    // 根据错误信息显示对应的提示
    let errorMessage = '生成订单失败，请稍后重试'
    
    // 从错误中获取后端返回的错误消息
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    // 使用Element Plus的消息提示
    ElMessage.error(errorMessage)
    isLoading.value = false
  }
}

const viewBookDetails = (id) => {
  router.push(`/book/${id}`)
}

// 修改调试方法，简化输出，移除alert
const debugCoverInfo = async () => {
  console.log('======= 封面调试信息 =======');
  console.log('书籍数据:', book.value);
  console.log('Cover属性:', book.value.cover);
  console.log('Cover类型:', typeof book.value.cover);
  
  if (!book.value.cover) {
    console.log('无封面数据，使用默认封面');
    return;
  }
  
  if (book.value.cover === 'true') {
    console.log('检测到cover=true，获取封面信息...');
    try {
      // 获取封面信息
      const response = await api.book.getCover(book.value.id);
      console.log('获取封面信息成功，完整响应:', response);
      
      if (response && response.cover) {
        console.log('发现封面路径:', response.cover);
        
        // 构建完整URL
        let imageUrl = '';
        if (!response.cover.startsWith('http')) {
          const encodedPath = response.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
          imageUrl = `http://localhost:8080/${encodedPath}`;
          console.log('构建的完整URL:', imageUrl);
        } else {
          imageUrl = response.cover;
        }
        
        // 更新封面
        coverUrl.value = imageUrl;
        console.log('封面已更新');
      } else {
        console.log('响应中没有cover字段，无法显示图片');
      }
    } catch (error) {
      console.error('获取封面信息失败:', error);
    }
    return;
  }
  
  // 处理其他情况
  if (typeof book.value.cover === 'string') {
    if (!book.value.cover.startsWith('http')) {
      // 相对路径，添加基础URL
      const encodedPath = book.value.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
      const testCoverUrl = `http://localhost:8080/${encodedPath}`;
      console.log('编码后的封面完整路径:', testCoverUrl);
      coverUrl.value = testCoverUrl;
    } else {
      // 已经是完整URL
      console.log('使用完整URL:', book.value.cover);
      coverUrl.value = book.value.cover;
    }
  } else {
    console.log('封面格式不正确，使用默认封面');
  }
  
  // 获取token信息
  const token = localStorage.getItem('token');
  console.log('当前token:', token ? '存在' : '不存在');
}

const openReportModal = () => {
  showReportModal.value = true
  reportData.value = {
    reason: '',
    details: ''
  }
}

const submitReport = async () => {
  // 表单验证
  if (!reportData.value.reason) {
    ElMessage.warning('请选择举报原因')
    return
  }
  
  if (!reportData.value.details || reportData.value.details.length < 10) {
    ElMessage.warning('请详细描述举报原因，至少10个字符')
    return
  }
  
  try {
    isSubmitting.value = true
    
    // 构造举报数据
    const data = {
      reported_id: book.value.seller_id,
      book_id: book.value.id,
      reason: reportData.value.reason,
      details: reportData.value.details
    }
    
    console.log('提交举报数据:', data)
    
    // 调用API提交举报
    const response = await api.report.create(data)
    
    console.log('举报API响应:', response)
    
    ElMessage.success('举报提交成功，我们会尽快处理')
    showReportModal.value = false
    
    // 重置表单
    reportData.value = {
      reason: '',
      details: ''
    }
  } catch (error) {
    console.error('提交举报失败:', error)
    
    // 提取错误信息
    let errorMessage = '举报提交失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.back-link {
  margin-bottom: 2rem;
}

.back-link a {
  color: #4b5563;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
}

.back-link a:hover {
  color: #3b82f6;
}

.book-content {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 3rem;
  margin-bottom: 3rem;
}

.book-image img {
  width: 100%;
  max-width: 400px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.book-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;
}

.view-count {
  display: flex;
  align-items: center;
  color: #6b7280;
  font-size: 0.9rem;
}

.view-count .el-icon {
  margin-right: 0.3rem;
  font-size: 1.1rem;
}

.book-details h1 {
  font-size: 2rem;
  color: #1f2937;
  margin-top: 0;
  margin-bottom: 0.5rem;
}

.book-author {
  color: #6b7280;
  margin-bottom: 1.5rem;
}

.book-price {
  font-size: 1.8rem;
  font-weight: bold;
  color: #ef4444;
  margin-bottom: 1.5rem;
}

.book-condition, .seller-info, .book-description {
  margin-bottom: 1.5rem;
}

.book-condition h3, .seller-info h3, .book-description h3 {
  font-size: 1.2rem;
  color: #374151;
  margin-bottom: 0.5rem;
}

.condition-meter {
  height: 8px;
  background-color: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.meter-fill {
  height: 100%;
  background-color: #3b82f6;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.btn-buy, .btn-contact, .btn-favorite {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-buy {
  background-color: #3b82f6;
  color: white;
}

.btn-buy:hover {
  background-color: #2563eb;
}

.btn-contact {
  background-color: #3b82f6;
  color: white;
}

.btn-contact:hover {
  background-color: #2563eb;
}

.btn-favorite {
  background-color: #f3f4f6;
  color: #4b5563;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-favorite:hover {
  background-color: #e5e7eb;
}

.favorite-icon {
  font-size: 1.2rem;
  transition: transform 0.2s;
}

.btn-favorite:hover .favorite-icon {
  transform: scale(1.2);
}

.btn-report {
  background-color: #ef4444;
  color: white;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-report:hover {
  background-color: #dc2626;
}

.recommended-books {
  margin-top: 3rem;
}

.recommended-books h2 {
  font-size: 1.5rem;
  color: #1f2937;
  margin-bottom: 1.5rem;
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 1.5rem;
}

.related-book {
  cursor: pointer;
  transition: transform 0.2s;
}

.related-book:hover {
  transform: translateY(-5px);
}

.related-book img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.related-info {
  padding: 0.5rem 0;
}

.related-info h4 {
  margin: 0.5rem 0;
  font-size: 1rem;
  color: #1f2937;
}

.related-info p {
  color: #ef4444;
  font-weight: 500;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  font-size: 1.2rem;
  color: #6b7280;
}

.contact-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 1.5rem;
}

.modal-body p {
  margin-bottom: 1rem;
}

.modal-body textarea {
  width: 100%;
  height: 100px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  padding: 0.5rem;
  margin-bottom: 1rem;
  resize: vertical;
}

.send-btn {
  padding: 0.75rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.send-btn:hover {
  background-color: #2563eb;
}

.no-recommendations {
  text-align: center;
  padding: 2rem;
  color: #6b7280;
  background-color: #f9fafb;
  border-radius: 8px;
}

.loading-icon {
  display: inline-block;
  width: 1.2rem;
  height: 1.2rem;
  border: 2px solid rgba(0, 0, 0, 0.1);
  border-top-color: #3b82f6;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .book-content {
    grid-template-columns: 1fr;
  }
  
  .book-image {
    text-align: center;
    margin-bottom: 2rem;
  }
  
  .book-image img {
    max-width: 300px;
  }
}

/* 添加调试按钮样式 */
.debug-btn {
  margin-top: 10px;
  padding: 5px 10px;
  background-color: #f59e0b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.debug-btn:hover {
  background-color: #d97706;
}

.report-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 1.5rem;
}

.modal-body p {
  margin-bottom: 1rem;
}

.modal-body textarea {
  width: 100%;
  height: 100px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  padding: 0.5rem;
  margin-bottom: 1rem;
  resize: vertical;
}

.report-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.form-group select, .form-group textarea {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
}

.report-info {
  margin-bottom: 1rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

.btn-submit, .btn-cancel {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-submit {
  background-color: #3b82f6;
  color: white;
}

.btn-submit:hover {
  background-color: #2563eb;
}

.btn-cancel {
  background-color: #f3f4f6;
  color: #4b5563;
}

.btn-cancel:hover {
  background-color: #e5e7eb;
}
</style> 